package com.schedule.controller;

import com.schedule.Util.PagedGridResult;
import com.schedule.pojo.Message;
import com.schedule.pojo.RespBean;
import com.schedule.service.IMessageService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/message")
public class MessageController {

    @Autowired
    private IMessageService messageService;

    @ApiOperation(value = "查询消息")
    @GetMapping("/queryMessage")
    @ResponseBody
    public RespBean queryAll(@RequestParam(name="page") Integer page,
                             @RequestParam(name="pageSize") Integer pageSize){  //分页查询消息
        PagedGridResult gridResult = messageService.findAll(page, pageSize);
        if (gridResult != null){
            return RespBean.success("查询消息成功",gridResult);
        }
        return RespBean.error("查询消息失败");
    }

    @ApiOperation(value = "设置消息")
    @PostMapping("/setMessage")
    @ResponseBody
    public RespBean insertMessage(@RequestParam("Title")String Title,
                                  @RequestParam("Content")String Content,
                                  @RequestParam("Publish_date")String Publish_date) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = dateFormat.parse(Publish_date);
        if (messageService.insertMessage(Title, Content, date)){
            return RespBean.success("设置消息成功");
        }
        return RespBean.error("设置消息失败");
    }

    @ApiOperation(value = "删除消息")
    @DeleteMapping("deleteMessage")
    @ResponseBody
    public RespBean delMessage(@RequestParam("Mid")Integer Mid){
        if (messageService.delMessage(Mid)){
            return RespBean.success("删除消息成功");
        }
        return RespBean.error("删除消息失败");
    }

    /**
     * 更新消息时前端需要获得原来的数据，然后一并传给后端
     */
    @ApiOperation(value = "更新消息")
    @PutMapping("updateMessage")
    @ResponseBody
    public RespBean updateMessage(@RequestParam("Title")String Title,
                                  @RequestParam("Author")String Author,
                                  @RequestParam("Content")String Content,
                                  @RequestParam("Publish_date")String Publish_date,
                                  @RequestParam("Role")String Role,
                                  @RequestParam("Mid")Integer Mid) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = dateFormat.parse(Publish_date);
        if (messageService.updateMessage(Title,Content, date, Mid)){
            return RespBean.success("更新消息成功");
        }
        return RespBean.error("更新消息失败");
    }
}
